package org.linlinjava.litemall.db.service;

import org.apache.commons.lang3.StringUtils;
import org.linlinjava.litemall.db.util.SequenceUtils;
import org.linlinjava.litemall.db.util.TransNoEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class TransNoGenerator {

    private static final Logger LOGGER = LoggerFactory.getLogger(TransNoGenerator.class);

    private static final int ACT_MAX = 200;

    /**
     * 序列号
     */
    private int actSeq;

    private volatile long lastTime;

    public TransNoGenerator() {
        lastTime = SequenceUtils.genDateTimeSeq();
    }

    public String genActNo(TransNoEnum noEnum) {
        long seq;
        synchronized (this) {
            long now = SequenceUtils.genDateTimeSeq();
            if (now > lastTime) {
                actSeq = 0;
            } else {
                if (actSeq == ACT_MAX) {
                    LOGGER.warn("序列号达到当天最大值[{}]，将重置", ACT_MAX);
                    now = SequenceUtils.tilNextSecond(lastTime);
                    actSeq = 0;
                }
            }
            lastTime = now;
            seq = actSeq++;
        }
        String pad = StringUtils.leftPad(String.valueOf(seq), 2, "0");
        return noEnum.name() + Long.valueOf(lastTime + pad + noEnum.getCode()) * 10;
    }


}
